package cn.cdtu.tibetplan.controller;

import java.util.ArrayList;
import java.util.List;
import cn.cdtu.tibetplan.pojo.*;
import cn.cdtu.tibetplan.service.MenuService;
import cn.cdtu.tibetplan.service.RolemenuService;
import cn.cdtu.tibetplan.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.cdtu.tibetplan.service.RoleService;

/**
 * controller
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RolemenuService rolemenuService;
    @Autowired
    private UserService userService;

    /**
     * 返回全部列表
     *
     * @return
     */
    @RequestMapping("/findAll")
    public List<Role> findAll() {
        return roleService.findAll();
    }


    @RequestMapping("/index")
    public String role() {
        return "redirect:search?currentPage=1&pageSize=15";
    }

    @RequestMapping("/search")
    public String search(User user, int currentPage, int pageSize, Model model) {
        PageResult result = userService.findPage(user, currentPage, pageSize);
        PageEnd pageend = new PageEnd(result.getTotal(), result.getRows(), currentPage, pageSize);
        model.addAttribute("pageEnd", pageend);
        return "/Role/index";
    }

    @RequestMapping("/roleEdit")
    public String roleEdit(Long id, Model model) {
        List<Role> roles = roleService.findAll();
        model.addAttribute("roles",roles);
        User user = userService.findOne(id.longValue());
        model.addAttribute("edit", user);
        return "/Role/edit";
    }

    @RequestMapping("/list")
    public String list(Model model) {
        List<Role> list = roleService.findAll();
        model.addAttribute("list", list);
        return "/Role/list";
    }

    @RequestMapping("/levelEdit")
    public String levelEdit(int roleId,Model model) {
        model.addAttribute("roleId",roleId);
        Rolemenu rm=new Rolemenu();
        rm.setRoleid(roleId);
        //PageResult rolePageResult = rolemenuService.findPage(rm, 1, 0);
        List<Rolemenu> roleRows = rolemenuService.findByRoleId(rm);//角色的菜单列表
        List<Integer> menuids=new ArrayList<>();//角色菜单id集合
        for(Rolemenu rlm:roleRows){
            if(rlm.getMenuid()!=0){
                menuids.add(rlm.getMenuid());
            }
        }
        System.out.println(menuids.size()+"333");
        List<Menus> allMenus = getAllMenus();
        for(Menus m:allMenus){
//            if(menuids.contains(m.getId())){
//                m.setChecked(true);
//            }
            List<Menus> children = m.getChildren();
            if(children!=null&&children.size()>0) {
                for (Menus ms : children) {
                    if (menuids.contains(ms.getId())) {
                        ms.setChecked(true);
                    }
                }
            }
        }
        model.addAttribute("menus", JSON.toJSONString(allMenus, SerializerFeature.DisableCircularReferenceDetect));
        System.out.println(JSON.toJSONString(allMenus,SerializerFeature.DisableCircularReferenceDetect));
        return "/Role/roleLevelEdit";
    }


    //保存角色权限
    @RequestMapping("/saveRoleMenu")
    @ResponseBody
    public Result saveRoleMenu(String  menus,int roleId){
//        System.out.println(menus);
//        TreeData treeData = JSON.parseObject(menus, TreeData.class);
//        List<Menus> ms = List<Menus>JSONObject.parseObject(menus, List.class);

//        ArrayList<Menus> ms  =JSON.parseObject(menus, new TypeReference<ArrayList<Menus>>(){});

        final List<Menus> ms = JSONArray.parseArray(menus, Menus.class);

//        System.out.println(treeData.getMenus().size());
        rolemenuService.deleteByRoleId(roleId);
        for(Menus m:ms){
            List<Menus> children = m.getChildren();
//            JSON.parseObject(m.getChildren(), new TypeReference<ArrayList<Menus>>(){});
            if(children!=null&&children.size()>0){
//                System.out.println(children.get(0).getId());
                for(Menus m2:children){
                        Rolemenu rm=new Rolemenu();
                        rm.setRoleid(roleId);
                        rm.setMenuid(m2.getId());
                        rolemenuService.add(rm);
                }
            }
        }
        return new Result(true,"修改成功");
    }

    //获取所有菜单
    private List<Menus> getAllMenus(){
        final List<Menu> menuRows = findMenuByPId(0);//一级菜单 pId=0
        List<Menus> result=new ArrayList<>();
        for(Menu mr:menuRows){
            List<Menu> childrenMenu = findMenuByPId(mr.getId());
            Menus ms=new Menus();
            ms.setId(mr.getId());
            ms.setHref(mr.getLink());
            ms.setTitle(mr.getName());
            ms.setSpread(true);
            if(childrenMenu.size()>0){
                List<Menus> children=new ArrayList<>();

                for(Menu m2:childrenMenu){
                    Menus mc=new Menus();
                    mc.setId(m2.getId());
                    mc.setTitle(m2.getName());
                    mc.setHref(m2.getLink());
                    mc.setSpread(true);
                    children.add(mc);
                }
                ms.setChildren(children);
            }
            result.add(ms);
        }
        return  result;
    }

    private List<Menu> findMenuByPId(int pId){
        Menu m=new Menu();
        m.setPid(pId);
        return menuService.findByPId(m);
    }

    /**
     * 返回全部列表
     *
     * @return
     */
    @RequestMapping("/findPage")
    public PageResult findPage(int page, int rows) {
        return roleService.findPage(page, rows);
    }

    /**
     * 增加
     *
     * @param role
     * @return
     */
    @RequestMapping("/add")
    public Result add(Role role) {
        try {
            roleService.add(role);
            return new Result(true, "增加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "增加失败");
        }
    }

    /**
     * 修改
     *
     * @param role
     * @return
     */
    @RequestMapping("/update")
    public Result update(@RequestBody Role role) {
        try {
            roleService.update(role);
            return new Result(true, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改失败");
        }
    }

    /**
     * 获取实体
     *
     * @param id
     * @return
     */
    @RequestMapping("/findOne")
    public Role findOne(Long id) {
        return roleService.findOne(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("/delete")
    public Result delete(Long[] ids) {
        try {
            roleService.delete(ids);
            return new Result(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
    }

//    /**
//     * 查询+分页
//     *
//     * @param page
//     * @param rows
//     * @return
//     */
//    @RequestMapping("/search")
//    public PageResult search(@RequestBody Role role, int page, int rows) {
//        return roleService.findPage(role, page, rows);
//    }

}
